package com.bosc.automationui.controller;

import com.bosc.automationui.service.ETLJobService;
import com.bosc.automationui.service.ScriptService;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping(value = "/jobinfo")
public class JobController {

    @Autowired
    ETLJobService etlJobService;

    @Autowired
    ScriptService scriptService;

    @DeleteMapping(value = "/{jobName}")
    public HashMap<String, Object> deleteJobStatus(@PathVariable String jobName) {
        return etlJobService.deleteById(jobName);
    }

    @PutMapping(value = "/{jobName}")
    public HashMap<String, Object> setJobStatusTypeVoid(@PathVariable String jobName) {
        return etlJobService.setVoid(jobName);
    }

    @PostMapping(value = "/{jobName}")
    public HashMap<String, Object> updateJobTxDate(@PathVariable String jobName, @RequestParam String date) {
        return etlJobService.updateDate(jobName, date);
    }

    @PutMapping(value = "/{jobName}/{scriptId}")
    public void recallScript(@PathVariable String jobName, @PathVariable String scriptId, @RequestParam String date) {
        scriptService.callScript(   jobName, scriptId, date);
    }

    @GetMapping("/{jobName}")
    public void download(@PathVariable String jobName, HttpServletResponse response) throws Exception {

        String filename = jobName + ".log";
        try (InputStream inputStream = new FileInputStream(new File(filename));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);

            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }

    @GetMapping("/search")
    public HashMap<String, Object> search(@RequestParam String col, @RequestParam String condition){

            return etlJobService.search(col,condition);
        }

}